<template>
  <el-form
    ref="fromdata1"
    :model="fromdata"
    :rules="rules"
    label-width="100px"
    label-position="right"
  >
    <base-layout
      :visibleContent1="true"
      :visibleContent2="true"
      :visibleContent3="true"
    >
      <template #contentPanel>
        <el-row>
          <el-col :span="12">供应商信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="供应商名称:" prop="supplierName">
              <el-input
                clearable
                v-model="fromdata.supplierName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商编码:" prop="supplierCode">
              <el-input
                clearable
                v-model="fromdata.supplierCode"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商类别:" prop="supplierType">
              <el-select
                clearable
                disabled
                ref="dragSelect"
                v-model="fromdata.supplierType"
                class="drag-select"
              >
                <el-option
                  v-for="item in dictArray['供应商类型']"
                  :key="item.id"
                  :value="item.value"
                  :label="item.text"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="所属城市:" prop="cityCode">
              <CitySelect v-model="fromdata.cityCode" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属区县:" prop="countyCode">
              <District
                :cityCode="fromdata.cityCode"
                v-model="fromdata.countyCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属门店:" prop="storeId">
              <JobShop
                clearable
                v-model="fromdata.storeId"
                @input="storeChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label-width="120px"
              label="精品类别:"
              prop="categoryIds"
            >
              <el-cascader
                clearable
                collapse-tags
                :value="goodTypeSelect"
                placeholder="请选择"
                :options="goodTypeTree"
                change-on-select
                :props="{
                  multiple: true,
                  checkStrictly: false,
                }"
                @change="handleGoodTypeChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="联系人:" prop="contactName">
              <el-input
                clearable
                v-model="fromdata.contactName"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="联系电话:" prop="contactPhone">
              <el-input
                clearable
                v-model.number="fromdata.contactPhone"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="供应商地址:" prop="address">
              <el-input
                clearable
                v-model="fromdata.address"
                placeholder="请输入地址，100字以内"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主营业务:" prop="note">
              <el-input
                type="textarea"
                placeholder="请输入"
                :rows="2"
                clearable
                v-model="fromdata.note"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注信息:">
              <el-input
                type="textarea"
                placeholder="请输入"
                :rows="2"
                clearable
                v-model="fromdata.remark"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel2>
        <el-row>
          <el-col :span="12">经营信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="公司全称:" prop="companyName">
              <el-input
                clearable
                v-model="fromdata.companyName"
                placeholder="公司全称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="公司法人:" prop="companyJuridical">
              <el-input
                clearable
                v-model="fromdata.companyJuridical"
                placeholder="公司法人"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item
              label="统一社会信用代码:"
              prop="companyCode"
              label-width="130px"
            >
              <el-input
                clearable
                v-model="fromdata.companyCode"
                placeholder="统一社会信用代码"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="成立日期:" prop="companyFoundingTime">
              <el-date-picker
                v-model="fromdata.companyFoundingTime"
                type="date"
                placeholder="成立日期"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </template>
      <template #contentPanel3>
        <el-row>
          <el-col :span="12">账号信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="登录名:" prop="account">
              <el-input
                :disabled="isEdit"
                clearable
                v-model="fromdata.account"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="密码:" prop="loginPwd">
              <el-input
                :type="isEdit ? 'password' : 'text'"
                :disabled="isEdit"
                clearable
                :password="password"
                v-model="fromdata.loginPwd"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="确认密码:" v-show="!isEdit" prop="confirmPwd">
              <el-input
                :disabled="isEdit"
                clearable
                v-model="fromdata.confirmPwd"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" align="right" justify="center">
            <el-button
              v-permission="
                !$route.params.id ? authConfig.add : authConfig.edit
              "
              type="success"
              @click="saveUpdate"
              >保存</el-button
            >
          </el-col>
        </el-row>
      </template>
    </base-layout>
  </el-form>
</template>
<script>
import baseMixin from '@/mixins/base'
import {
  updateData,
  addData,
  details,
  getGoodTypeTree,
} from '@/api/pre-sale/supplierManage/supplierManage'
import CityDistrictSelector from '@/components/CityDistrictSelector/index'
import { getDict, parseTimeToYMDHMS } from '@/utils'
import { phoneCheck } from '@/utils/rulesFunction'
import { rules } from './rules/index'
import { passwordCheck, accountCheck } from '@/utils/rulesFunction'

export default {
  components: {
    CityDistrictSelector,
  },
  mixins: [
    baseMixin({
      addData: addData,
      updateData: updateData,
      format(res) {
        return res.map((data) => {
          return data
        })
      },
    }),
  ],
  data() {
    return {
      authConfig: {
        add: 'supplier:jp:create',
        edit: 'supplier:jp:update',
      },
      isEdit: false, // 新增还是编辑
      isEditFirst: false, // 编辑请求数据不要制空精品类别
      fromdata: {
        status: true,
        supplierName: '', // 供应商名称
        supplierCode: '', // 供应商编码
        supplierType: '精品供应商', // 供应商类别
        cityCode: '', // 城市编码
        countyCode: '', // 区县编码
        storeId: '',
        id: '',
        contactName: '', // 联系人
        contactPhone: '', // 联系电话
        address: '', // 供应商地址
        note: '', // 主营业务
        remark: '', // 备注信息
        companyName: '', // 公司全称
        companyJuridical: '', // 公司法人
        companyCode: '', // 统一社会信用代码
        companyFoundingTime: '', // 成立日期
        categoryIds: '', // 精品一类二类ID，用逗号隔开。
        account: '', // 登录账号
        loginPwd: '', // 登录密码
        confirmPwd: '', // 确认密码
      },
      goodTypeSelect: [], // 勾选中的精品类别
      goodTypeTree: [], // 精品类别树
      rules: {
        ...rules,
        account: [
          {
            required: true,
            trigger: 'blur',
            validator: accountCheck,
          },
        ],
        loginPwd: [
          {
            required: true,
            trigger: 'blur',
            validator: passwordCheck,
          },
        ],
        confirmPwd: [
          {
            required: true,
            trigger: 'blur',
            validator: (rule, value, callback) => {
              if (value && this.fromdata.loginPwd == value) {
                callback()
              } else {
                callback('密码一致')
              }
            },
          },
        ],
      },
      dictArray: [],
    }
  },
  methods: {
    // 监听城市区县组件返回值
    cityValue(value) {
      this.fromdata.cityCode = value[0]
      this.fromdata.countyCode = value[1]
    },
    // 门店切换重置精品列别
    storeChange(newValue) {
      // 编辑查询，不要置空精品类别
      if (!this.isEditFirst) {
        this.goodTypeSelect = []
        this.fromdata.categoryIds = ''
      } else {
        this.isEditFirst = false
      }
      this.$refs['fromdata1'].validateField('categoryIds')
      this.getGoodTypeTree(newValue)
    },
    // 精品类别勾选
    handleGoodTypeChange(value) {
      this.fromdata.categoryIds = ''
      this.goodTypeSelect = value
      let arr = []
      let categoryString = ''
      value.forEach((item) => {
        arr = arr.concat(item)
      })
      // 过滤数组拼接成字符，用逗号隔开
      Array.from(new Set(arr)).forEach((item) => {
        if (categoryString === '') {
          categoryString = categoryString + item
        } else {
          categoryString = categoryString + ',' + item
        }
      })
      this.fromdata.categoryIds = categoryString
      this.$refs['fromdata1'].validateField('categoryIds')
    },

    // 保存数据
    saveUpdate() {
      this.$refs['fromdata1'].validate((valid) => {
        if (valid) {
          let options = this.fromdata
          options.companyFoundingTime = options.companyFoundingTime
            ? parseTimeToYMDHMS(options.companyFoundingTime)
            : ''
          this.saveSuppierData()
        }
      })
    },

    async saveSuppierData() {
      const { success } = this.fromdata.id
        ? await updateData(this.fromdata)
        : await addData(this.fromdata)
      if (success) {
        this.$message({
          message: '操作成功',
          type: 'success',
        })
        this.$router.push({ path: '/supplierManage/goodSupplierManage' })
      } else {
        this.$message.error('操作失败')
      }
    },
    // 查询详情
    async detail(id) {
      let { data } = await details(id)
      this.fromdata = data
      this.fromdata.confirmPwd = data.loginPwd
    },
    // 根据门店查询精品类别树
    async getGoodTypeTree(storeId) {
      let { data } = await getGoodTypeTree({ storeId })
      this.goodTypeTree = data
    },
    // 编辑根据返回精品类别值转为级联选择绑定格式
    getTreeSelectValue() {
      let select = []
      if (this.fromdata.categoryIds) {
        const categoryIds = this.fromdata.categoryIds.split(',')
        this.goodTypeSelect = categoryIds.map((item) => {
          for (let i = 0; i < this.goodTypeTree.length; i++) {
            let treeItem = this.goodTypeTree[i]
            if (JSON.parse(item) === JSON.parse(treeItem.value)) {
              return [treeItem.value]
            } else if (treeItem.children) {
              for (let j = 0; j < treeItem.children.length; j++) {
                let treeChildItem = treeItem.children[j]
                if (JSON.parse(item) === JSON.parse(treeChildItem.value)) {
                  return [treeItem.value, treeChildItem.value]
                }
              }
            }
          }
        })
        // this.handleGoodTypeChange(this.goodTypeSelect)
      }
    },
  },
  mounted() {},
  created() {
    this.dictArray = getDict(['供应商类型'])
    const id = this.$route.query && this.$route.query.id
    if (id) {
      this.rules = { ...rules }
      this.isEdit = true
      this.isEditFirst = true
      this.fromdata.id = id
      this.detail(id).then(() => {
        this.getGoodTypeTree(this.fromdata.storeId).then(() => {
          this.getTreeSelectValue()
        })
      })
    }
  },
}
</script>
<style lang="scss" scoped>
</style>
